<template>
  <el-dialog
    :title="form.eventId ? '编辑人生大事' : '添加人生大事'"
    :model-value="visible"
    @update:modelValue="$emit('update:visible', $event)"
    width="600px"
    @close="resetForm"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="事件类型" prop="eventType">
        <el-select v-model="form.eventType" placeholder="请选择事件类型" style="width: 100%;">
          <el-option
            v-for="item in eventTypes"
            :key="item.itemId"
            :label="item.itemName"
            :value="item.itemName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="事件日期" prop="eventDate">
        <el-date-picker
          v-model="form.eventDate"
          type="date"
          placeholder="选择或输入日期 (YYYY-MM-DD)"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :editable="true"
          :clearable="true"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="事件描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入事件的详细描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import type { EventFormData, CommonType } from '@/types/api';
import { addEventApi, updateEventApi } from '@/api/person';
import { getCommonDictApi } from '@/api/common';

const props = defineProps<{
  visible: boolean;
  personId: number;
  eventData?: EventFormData | null; // 用于编辑时传入事件数据
}>();

const emit = defineEmits(['update:visible', 'success']);

const formRef = ref<FormInstance>();
const loading = ref(false);
const eventTypes = ref<CommonType[]>([]); // 存储事件类型字典数据

const form = reactive<EventFormData>({
  personId: props.personId,
  eventType: '',
  eventDate: '',
  description: '',
});

const rules: FormRules = {
  eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  eventDate: [{ required: true, message: '请选择或输入事件日期', trigger: 'change' }],
};

// 加载事件类型字典数据
const fetchEventTypes = async () => {
  try {
    eventTypes.value = await getCommonDictApi(2); // groupId 2 代表事件类型
  } catch (error) {
    console.error("Failed to fetch event types:", error);
    ElMessage.error("加载事件类型失败");
  }
};

// 当组件挂载时加载事件类型
onMounted(fetchEventTypes);

// 监听 props.eventData 变化，用于编辑模式
watch(
  () => props.eventData,
  (newData) => {
    if (newData) {
      // 复制传入的数据到表单，确保响应式
      Object.assign(form, newData);
    } else {
      // 如果是新增模式，重置表单
      resetForm();
    }
  },
  { immediate: true } // 立即执行一次，处理初始值
);

const resetForm = () => {
  form.eventId = undefined;
  form.eventType = '';
  form.eventDate = '';
  form.description = '';
  form.personId = props.personId; // 确保 personId 始终正确
  formRef.value?.resetFields(); // 重置表单验证状态
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (form.eventId) {
          // 编辑事件
          await updateEventApi(form.eventId, form);
          ElMessage.success('事件更新成功！');
        } else {
          // 添加新事件
          await addEventApi(form);
          ElMessage.success('事件添加成功！');
        }
        emit('success'); // 通知父组件数据已更新
        emit('update:visible', false); // 关闭对话框
      } catch (e) {
        console.error("提交事件失败:", e);
        ElMessage.error('提交事件失败，请稍后再试。');
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>

watch(() => props.visible, (val) => {
  if (val) {
    fetchEventTypes(); // 打开对话框时重新加载事件类型
  } else {
    resetForm(); // 关闭对话框时重置表单
  }
});
</style>
